package com.coolwen.spring.dao;/**
 * Created by CoolWen on 2017/11/16.
 */

import com.coolwen.spring.model.Group;
import com.coolwen.spring.model.User;

import org.hibernate.query.Query;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author CoolWen
 * @version 2017-11-16 20:43
 */
@Repository("userDao")
public class UserDao extends BaseDao implements IUserDao {
    private IGroupDao groupDao;

    public IGroupDao getGroupDao() {
        return groupDao;
    }

    @Resource
    public void setGroupDao(IGroupDao groupDao) {
        this.groupDao = groupDao;
    }

    @Override
    public void add(User user, int gid) {
        Group group = groupDao.load(gid);
        user.setGroup(group);
        this.getSession().save(user);
    }

    @Override
    public void update(User user) {
        this.getSession().update(user);
    }

    @Override
    public void delete(int id) {
        User u = this.getSession().load(User.class, id);
        this.getSession().delete(u);
    }

    @Override
    public User load(int id) {
        return this.getSession().load(User.class, id);
    }


    @Override
    public List<User> list(String hql, Object[] args) {
        Query q = this.getSession().createQuery(hql);
        if(args!=null) {
            for(int i=0;i<args.length;i++) {
                q.setParameter(i, args[i]);
            }
        }
        return q.list();

    }
}
